import { Modal, Pagination, notification } from 'antd';
import { useEffect, useMemo, useState } from 'react';
import { LockTwoTone, UnlockTwoTone, ApiTwoTone, SmileOutlined, BugOutlined } from '@ant-design/icons';
import { memo } from 'react';
import Mahjong from 'components/Mahjong';
import { getGroupInfo } from '@/api/modules/group';
import { getCardsDetail } from 'api/cards';
import useRefState from 'hooks/useRefState';
import { HOME_URL } from '@conf';
import { useLocation, useNavigate, useParams } from 'react-router-dom';
import { connect } from 'react-redux';
import EasyMahjongGroup from 'components/Mahjong/easyGroup';

type BaseType = {
	deck: Array<number>;
	partition: Array<number>;
	linner: Record<string, Array<number>>;
	name?: string;
	id?: number;
	u_id?: number;
	createtime?: string;
	updatetime?: string;
};

type groupInfoType = {
	cards: Array<{ card_id: number; u_id: number; name: string }>;
	createtime?: string;
	updatetime?: string;
	u_id?: number;
	name: string;
	id?: number;
};

let externalTools: any;
const notifiKey: string = 'VOEWIHGOILWNHKGF';
const mapStateToProps = ({ conf }: any) => ({ ...conf });
const BASE_IMAGE = import.meta.env.VITE_IMG_URL as string;
function getHerf(imageURL: string) {
	return imageURL.includes('//') ? imageURL : BASE_IMAGE + imageURL;
}
export default connect(
	mapStateToProps,
	null
)(
	memo(function (props: any) {
		const navigator = useNavigate();
		const { groupId } = useParams();
		const [open, setOpen] = useState(false);
		const [lock, setLock, lockRef] = useRefState(false); // 禁止监听
		const [groupInfo, setGroupInfo, groupInfoRef] = useRefState<groupInfoType>({ cards: [], name: '' }); // 牌组数据
		const [baseInfo, setBaseInfo, baseInfoRef] = useRefState<BaseType>({ deck: [], partition: [], linner: {} }); // 牌型数据
		const [current, setcurrent] = useState(1); // 页码
		const [mahjongs, setMahjongs, mahjongsRef] = useRefState<Array<{ id: Number; active?: boolean; right?: boolean }>>(
			[]
		); // 当前麻将牌数据
		const [linners, setLinners] = useState([{}]);
		const [notificationApi, contextHolder] = notification.useNotification();

		const linnerKeys = useMemo(() => {
			const { linner } = baseInfo;
			const keys = Object.keys(linner);
			externalTools && externalTools.postMessage({ linnerKeys: keys });
			return keys;
		}, [baseInfo]);

		function checkLinner(showmessage?: boolean) {
			const active_mahjongs = mahjongsRef.current.filter(({ active }) => active);
			const active_key = active_mahjongs.map(({ id }) => id).join(',');
			const value = baseInfoRef.current.linner[active_key];
			let msg: string = '';
			let showmj: Array<any> = [];
			if (value) {
				showmj = value.map((id: number | string) => ({
					right: false,
					id,
				}));
			}
			setLinners(showmj);

			showmessage &&
				notificationApi.open({
					duration: 2,
					key: notifiKey,
					message: value ? '非常棒' : '很遗憾',
					description: value ? '回答正确' : '回答错误',
					icon: value ? <SmileOutlined style={{ color: '#108ee9' }} /> : <BugOutlined style={{ color: 'red' }} />,
				});
		}

		function nextStep() {
			const { partition } = baseInfoRef.current;
			const newdata = mahjongsRef.current.map((e, i: number) => {
				e.right = partition.includes(i);
				// e.active = false
				return e;
			});
			setMahjongs(newdata);
		}

		function init() {
			const { deck } = baseInfoRef.current;
			setMahjongs(deck.map((id) => ({ id })));
			setLinners([]);
		}

		let escCount: number = 0;
		let escTimeout: any;
		const { prev_key, next_key, init_key, split_key, linner_key, message_linner_key } = props;
		function onkeydown({ key }: any) {
			escTimeout && clearTimeout(escTimeout);
			if (key === 'Escape') {
				escCount += 1;
				escTimeout = setTimeout(() => {
					if (escCount >= 3) {
						clearTimeout(escTimeout);
						navigator(HOME_URL);
					}
					escCount = 0;
				}, 500);
			} else escCount = 0;
			if (lockRef.current) return;
			switch (key) {
				case split_key:
					return nextStep();
				case init_key:
					return init();
				case linner_key:
					return checkLinner();
				case message_linner_key:
					return checkLinner(true);
				case prev_key:
					setcurrent((current) => {
						current = current - 1 || groupInfoRef.current.cards.length; // 越界：循环
						currentChange(current);
						return current;
					});
					return;
				case next_key:
					setcurrent((current) => {
						current = current + 1;
						console.log(groupInfoRef.current.cards.length);
						if (current > groupInfoRef.current.cards.length) current = 1; // 越界：循环
						currentChange(current);
						return current;
					});
					return;
			}
		}

		async function currentChange(page: number) {
			const id = groupInfoRef.current.cards[page - 1].card_id;
			const resdata = await getCardsDetail(id);
			setBaseInfo(resdata);
			setcurrent(page);
			externalTools && externalTools.postMessage({ current: page });
			setTimeout(() => {
				init();
			}, 300);
		}

		useEffect(() => {
			getGroupInfo(Number(groupId)).then(async (data) => {
				setGroupInfo(data);
				const { cards } = data;
				if (!cards || !cards.length)
					return Modal.error({
						title: '提示',
						content: '该牌组未包含任何牌型',
						onOk: () => {
							navigator('/useruse/mahjongopen');
						},
					});
				currentChange(1);
			});
			window.addEventListener('keydown', onkeydown);
			return () => {
				window.removeEventListener('keydown', onkeydown);
			};
		}, [groupId]);

		let LinnerInter: any;
		// 打开外部工具栏
		function openExternalTools() {
			if (externalTools && !externalTools.closed) return;
			const { pathname, origin } = window.location;
			externalTools = window.open(
				`${origin}${pathname}#/useruse/mahjongtools/${groupId}`,
				'',
				'top=300,titlebar=no,toolbar=no,height=700,width=484'
			);
			setOpen(() => {
				setTimeout(() => {
					externalTools.postMessage({ current, linnerKeys, groupInfo });
				}, 1000);
				LinnerInter = setInterval(() => {
					console.log('检查');
					if (!externalTools || externalTools.closed) {
						clearInterval(LinnerInter);
						setOpen(false);
					}
				}, 500);
				return true;
			});
		}

		function messageByChild() {
			setTimeout(() => {
				externalTools.postMessage({ groupInfo, baseInfo, mahjongs });
			}, 2000);
		}

		useEffect(() => {
			window.addEventListener('message', messageByChild);
			return () => {
				externalTools && !externalTools.closed && externalTools.close();
				clearInterval(LinnerInter);
				window.removeEventListener('message', messageByChild);
			};
		}, []);

		return (
			<>
				{contextHolder}
				<div className=' cur_default h-screen w-screen box-border bg-cover flex flex-col'>
					<div
						style={{
							backgroundColor: '#458690',
							backgroundImage: `url(${getHerf(props.bg_url)})`,
							backgroundPosition: 'center',
						}}
						className=' h-full w-full bg-no-repeat bg-cover text-center flex flex-col'>
						<div className=' m-auto'>
							<div className=' my-8 min-h-48 w-full box-border'>
								{mahjongs.map((mahjong: any, index: number) => (
									<Mahjong
										mahjong={mahjong}
										key={'mj1-' + index}
										changeMargin={(attr: string) => {
											mahjong[attr] = !mahjong[attr];
											setMahjongs([...mahjongs]);
										}}
									/>
								))}
							</div>
							<div className=' my-8 min-h-48 w-full box-border'>
								{linners.map((mahjong: any, index: number) => (
									<Mahjong mahjong={mahjong} key={'mj2-' + index} changeMargin={() => {}} />
								))}
							</div>
						</div>
						{open && <div className=' h-6 cursor-move electron-move'></div>}
					</div>
					{!open && (
						<div className=' mt-auto bg-white flex h-32 overflow-hidden electron-move'>
							<div className=' flex flex-col p-2 flex-shrink-0 relative electron-move-dis'>
								<div className=' flex-1 h-0 overflow-y-scroll'>
									<p className=' font-bold'>
										{groupInfo.name}:{groupInfo.cards.length}
									</p>
									<p className=' text-sm text-gray-400'>-- {baseInfo.name}</p>
								</div>
								<Pagination
									simple
									current={current}
									onChange={(i) => {
										currentChange(i);
									}}
									pageSize={1}
									total={groupInfo.cards.length}
								/>
								<i className=' icon-class absolute top-0 right-8' onClick={openExternalTools}>
									<ApiTwoTone />
								</i>
								<i
									className=' icon-class absolute top-0 right-0'
									onClick={() => {
										setLock(!lock);
									}}>
									{lock ? <LockTwoTone /> : <UnlockTwoTone />}
								</i>
							</div>
							<div className=' p-2 flex-1 w-0'>
								<p className=' mb-2 text-xs font-mono font-bold'>监听牌组：</p>
								<div className=' flex gap-2 overflow-x-scroll'>
									{linnerKeys.map((e, index) => (
										<div key={'linn-' + index} className=' bg-blue-50 p-2 rounded whitespace-nowrap'>
											{EasyMahjongGroup({
												list: e.split(','),
											})}
										</div>
									))}
								</div>
							</div>
						</div>
					)}
				</div>
			</>
		);
	})
);
